package mornd.test1.custom;

import mornd.test1.annotation.Yml;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.yaml.snakeyaml.Yaml;

import javax.servlet.http.HttpServletResponse;

/**
 * @author: mornd
 * @dateTime: 2023/5/7 - 17:19
 */
public class YmlReturnValueHandler implements HandlerMethodReturnValueHandler {
    /**
     *
     * @param returnType 返回值类型
     * @return
     */
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return returnType.getMethodAnnotation(Yml.class) != null;
    }

    /**
     * 解析
     * @param returnValue 真正的返回值
     * @param returnType
     * @param mavContainer
     * @param webRequest 即封装了 request，也封装了 response
     * @throws Exception
     */
    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType,
                                  ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest) throws Exception {
        String yml = new Yaml().dump(returnValue);
        // 获取 response 对象
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/plain;charset=utf-8");
        response.getWriter().print(yml);

        // 告知 spring 请求已经处理完毕，不需要 spring 再额外做后续处理了
        mavContainer.setRequestHandled(true);
    }
}
